﻿using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;

namespace Tisonet.Dobrak.Adapters
{
    public class PhoneIsolatedStorageAdapter : IIsolatedStorage
    {     
        public bool HasSettings(string key)
        {
            return IsolatedStorageSettings.ApplicationSettings.Contains(key);
        }

        public T GetSettings<T>(string key)
        {
            if (HasSettings(key))
            {
                return (T) IsolatedStorageSettings.ApplicationSettings[key];
            }
            
            throw new KeyNotFoundException(key);
        }

        public T GetSettingsOrDefault<T>(string key, T defaultValue)
        {
            if (HasSettings(key))
            {
                return (T)IsolatedStorageSettings.ApplicationSettings[key];
            }

            return defaultValue;
        }

        public void SaveSettings(string key, object value)
        {
            IsolatedStorageSettings.ApplicationSettings[key] = value;
           
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        public bool HasFile(string filename)
        {
            using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                return isoFile.FileExists(filename);
            }
        }

        public string ReadFile(string filename)
        {
            using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isoFile.FileExists(filename))
                {
                    using (Stream isoStream = isoFile.OpenFile(filename, FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(isoStream))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                throw new FileNotFoundException(filename);
            }
        }

        public void WriteToFile(string filename, string content)
        {
            using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (Stream isoStream = isoFile.OpenFile(filename, FileMode.Create))
                {
                    using (StreamWriter writer = new StreamWriter(isoStream))
                    {
                        writer.WriteLine(content);
                    }
                }
            }
        }
    }
}
